using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Deepcode.Flux.Core.Data;
using Deepcode.Flux.Core.Services.Assistant;
using Deepcode.Flux.Core.Services.Configuration;
using Deepcode.Flux.Core.Systems.Workflow;
using Deepcode.Flux.Core.Systems.Workflow.Bases;
using Deepcode.Flux.Core.Systems.Workflow.Info;
using Deepcode.Flux.Core.Systems.Workflow.Enums;
using Deepcode.Flux.Core.Services.State;
using Deepcode.Flux.Core.Extensions;
using Deepcode.Flux.Core.Systems.Audit.Quick;

public partial class Private_Config_Workflow_ui_usertask : Deepcode.Flux.Core.UI.AdministrationModulePage
{
	#region Permission Code Override
	public override string RequiredPermissionCode { get { return "FluxWorkflowEdit"; } }
	#endregion
	#region ViewState storage
	/// <summary>
	/// Stores the ID of the handler which this form
	/// is adding a new definition to.
	/// </summary>
	public string HandlerID
	{
		get
		{
			object o = ViewState["HandlerID"];
			if (o == null) return String.Empty;
			return (string)o;
		}
		set
		{
			ViewState["HandlerID"] = value;
		}
	}
	/// <summary>
	/// Stores the ID of the definition being edited
	/// </summary>
	public int DefinitionID
	{
		get
		{
			object o = ViewState["DefinitionID"];
			if (o == null) return -1;
			return (int)o;
		}
		set
		{
			ViewState["DefinitionID"] = value;
		}
	}
	/// <summary>
	/// Stores the ID of the process being edited
	/// </summary>
	public int ProcessID
	{
		get
		{
			object o = ViewState["ProcessID"];
			if (o == null) return -1;
			return (int)o;
		}
		set
		{
			ViewState["ProcessID"] = value;
		}
	}
	/// <summary>
	/// Stores the ID of the tasking being edited
	/// </summary>
	public int TaskingID
	{
		get
		{
			object o = ViewState["TaskingID"];
			if( o == null ) return -1;
			return (int) o;
		}
		set
		{
			ViewState["TaskingID"] = value;
		}
	}
	#endregion
	#region Page Load Event
	/// <summary>
	/// Page Load event
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void Page_Load(object sender, EventArgs e)
	{
		if (!Page.IsPostBack)
		{
			// Store any state information from the calling listing
			this.HandlerID = GetAttribute("HandlerID", "");
			this.DefinitionID = GetAttribute("DefinitionID", -1);
			this.ProcessID = GetAttribute("ProcessID", -1);
			this.TaskingID = GetAttribute("TaskingID", -1);

			// Load info 
			Handler h = new Handlers().GetHandlerByID( this.HandlerID );
			if( h == null ) GoBack();
			Definition d = new Definitions().GetByID( this.DefinitionID );
			if( d == null ) GoBack();
			Process p = new Processes().GetProcessByID( this.ProcessID );
			if( p == null ) GoBack();
			Tasking t = new Taskings().GetTaskingByID( this.TaskingID );
			if( t == null ) GoBack();
			
			// Display infos
			labHandler.Text = h.Name;
			labDefinition.Text = d.DefName;
			labProcess.Text = p.ProcessName;
			labTasking.Text = t.TaskCaption;

			// Get data for the various selections etc
			WorkflowEngine Engine = new WorkflowEngine( this.HandlerID );
			if( Engine == null ) GoBack();

			// Create arrays of the various selections
			ArrayList SelectedOperators = new ArrayList(t.CSV_OperatorID.Split(','));
			ArrayList SelectedGroups = new ArrayList(t.CSV_GroupID.Split(','));

			// GetWorkflowTaskableOperators
			this.CSV_GroupID.Items.Clear();
			foreach (WorkflowTaskableOperator wto in Engine.GetTaskableOperators())
			{
				ListItem i = new ListItem(wto.OperatorName, wto.OperatorID.ToString());
				if (SelectedOperators.Contains(wto.OperatorID.ToString())) i.Selected = true;
				this.CSV_OperatorID.Items.Add(i);
			}

			// GetWorkflowTaskableOperatorGroups();
			this.CSV_GroupID.Items.Clear();
			foreach (WorkflowTaskableGroup wtg in Engine.GetTaskableGroups())
			{
				ListItem i = new ListItem(wtg.GroupName, wtg.GroupID.ToString());
				if (SelectedGroups.Contains(wtg.GroupID.ToString())) i.Selected = true;
				this.CSV_GroupID.Items.Add(i);
			}

			// GetWorkflowTaskableSpecialMethods();
			this.GetUserMethod.Items.Clear();
			foreach (WorkflowTaskableMethodInfo info in Engine.GetWorkflowTaskableMethods())
			{
				ListItem i = new ListItem(info.FriendlyName, info.MethodName);
				if (t.GetUserMethod == info.MethodName) i.Selected = true;
				this.GetUserMethod.Items.Add(i);
			}

			TaskCaption.Text = t.TaskCaption;
			ActivateTask.TimescaleUnit = t.ActivateTaskAtUnit;
			ActivateTask.NumberOfUnits = t.ActivateTaskAt;
			DeadlineTask.TimescaleUnit = t.DeadlineTaskAtUnit;
			DeadlineTask.NumberOfUnits = t.DeadlineTaskAt;

			BindExitPathsGrid();
		}
	}
	#endregion
	#region Page_Init Event
	/// <summary>
	/// Page is initialising, hook up the grid command handler
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void Page_Init(object sender, EventArgs e)
	{
		datagrid.ItemCommand += new DataGridCommandEventHandler(datagrid_ItemCommand);
	}
	#endregion
	#region Navigation
	/// <summary>
	/// Returns to process editor
	/// </summary>
	protected void GoBack()
	{
		string url = String.Format(
			"ui_ProcessForm.aspx?HandlerID={0}&DefinitionID={1}&ProcessID={2}", 
			this.HandlerID,
			this.DefinitionID,
			this.ProcessID);
		
		Response.Redirect(url, true);
	}
	#endregion
	#region Save/Cancel handlers
	/// <summary>
	/// User cancelled the save, go back to previous page
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void btnCancel_Click(object sender, EventArgs e)
	{
		GoBack();
	}
	/// <summary>
	/// User clicked the save button, store the data
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void btnSave_Click(object sender, EventArgs e)
	{
		if (!Page.IsValid) return;

		Tasking  t = new Taskings().GetTaskingByID( this.TaskingID );
		if( t== null ) GoBack();
		t.TaskCaption = this.TaskCaption.Text;
		t.CSV_OperatorID = ControlUtil.GetListSelectedCSV( this.CSV_OperatorID.Items );
		t.CSV_GroupID = ControlUtil.GetListSelectedCSV( this.CSV_GroupID.Items );
		t.GetUserMethod = this.GetUserMethod.SelectedValue;
		t.ActivateTaskAt = ActivateTask.NumberOfUnits;
		t.ActivateTaskAtUnit = ActivateTask.TimescaleUnit;
		t.DeadlineTaskAt = DeadlineTask.NumberOfUnits;
		t.DeadlineTaskAtUnit = DeadlineTask.TimescaleUnit;

		Taskings taskings = new Taskings();
		taskings.Save(t);

		QuickAudit.RaiseInformation(
			new AuditUser(),
			"Flux", "Workflow Manager",
			"edited tasking ({0}) in process ({1})",
			t.TaskCaption,
			t.ParentProcess.ProcessName);
	}
	#endregion
	#region Exit paths grid
	/// <summary>
	/// Bind list of exit paths to the data grid
	/// </summary>
	protected void BindExitPathsGrid()
	{
		datagrid.BindJavascript("btnDelete", "onclick", "return ConfirmDelete();");
		
		TaskExitPaths teps = new TaskExitPaths();
		datagrid.DataSource = teps.GetExitPathsForTaskingID( this.TaskingID );
		datagrid.DataBind();
	}
	/// <summary>
	/// User clicked the add exit path button
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void btnAddExit_Click(object sender, EventArgs e)
	{
		string url = String.Format(
			"ui_newexitpath.aspx?HandlerID={0}&DefinitionID={1}&ProcessID={2}&TaskingID={3}",
				this.HandlerID,
				this.DefinitionID,
				this.ProcessID,
				this.TaskingID);

		Response.Redirect(url, true);
	}
	/// <summary>
	/// User has interacted with the grid
	/// </summary>
	/// <param name="source"></param>
	/// <param name="e"></param>
	void datagrid_ItemCommand(object source, DataGridCommandEventArgs e)
	{
		if (e.Item.ItemType == ListItemType.Footer ||
			e.Item.ItemType == ListItemType.Header ||
			e.Item.ItemType == ListItemType.Pager ||
			e.Item.ItemType == ListItemType.Separator) return;

		// Get the key of the row being actioned 
		int rowKey = (int)datagrid.DataKeys[e.Item.ItemIndex];

		// PROCESS COMMANDS
		if (e.CommandName == "ItemDelete")
		{
			TaskExitPaths teps = new TaskExitPaths();
			TaskExitPath  tep = teps.GetTaskExitPathByID( rowKey );
			if( tep == null ) return;

			teps.DeleteByID( rowKey );
			this.BindExitPathsGrid();

			Tasking pt = tep.ParentTasking;
			Process pp = pt.ParentProcess;

			QuickAudit.RaiseInformation(
				new AuditUser(),
				"Flux", "Workflow Manager",
				"deleted exit path ({0} from tasking ({1}) from process ({2})",
				tep.Caption,
				pt.TaskCaption,
				pp.ProcessName );
		}

		if (e.CommandName == "ItemEdit")
		{
			string url = String.Format(
				"ui_exitpath.aspx?HandlerID={0}&DefinitionID={1}&ProcessID={2}&TaskingID={3}&TaskExitPathID={4}",
					this.HandlerID,
					this.DefinitionID,
					this.ProcessID,
					this.TaskingID,
					rowKey);
			Response.Redirect(url, true);
		}
	}
	#endregion
}
